package ext.tianma.bom.service;

import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.httpgw.HTTPRequest;
import wt.httpgw.HTTPResponse;
import wt.inf.container.ExchangeContainer;
import wt.inf.container.OrgContainer;
import wt.inf.container.WTContainerHelper;
import wt.inf.container.WTContainerRef;
import wt.method.MethodContext;
import wt.org.DirectoryContextProvider;
import wt.org.GenericDirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.UserNotFoundException;
import wt.org.WTOrganization;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.pds.StatementSpec;
import wt.pom.WTConnection;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;

public class SelectUserService {

	private static List<String> userNameList;


	public static WTUser createWTUser(String userNo, String userName, String fullName, String mail, String department, String telephone, String eng_name, String firstName)
		throws WTException, WTPropertyVetoException
	{
		WTUser user = null;
		WTContainerRef ref = WTContainerHelper.getExchangeRef();
		ExchangeContainer exc = (ExchangeContainer)ref.getObject();
		WTOrganization org = findWTOrganization("tm");
		OrgContainer orgcontainer = WTContainerHelper.service.getOrgContainer(org);
		user = getUserByName(userName);
		System.out.println("userName=====>>>"+userName);
		if (user == null)
		{
			System.out.println("===start===>>创建开始==>>");
			WTPrincipal currUser = SessionHelper.manager.getPrincipal();
			SessionHelper.manager.setAdministrator();
			user = WTUser.newWTUser(userNo, exc.getContextProvider());
			user.setAttributes(OrganizationServicesHelper.manager.createAttributeHolder());
			user.getAttributes().addValue("userPassword", "windchill");
			user.getAttributes().addValue("uid", eng_name);
			if (department != null && !department.equals(""))
				fullName = (new StringBuilder(String.valueOf(fullName))).append("(").append(department).append(")").toString();
			user.setFullName(fullName);
			user.setLast("test");
			user.setFirst(firstName);
			user.setEMail(mail);
			user.setPostalAddress(department);
			user.setTelephoneNumber(telephone);
			user.setOrganizationName(orgcontainer.getName());
			user = (WTUser)OrganizationServicesHelper.manager.createPrincipal(user);
			System.out.println("创建成功===》》》");
			SessionHelper.manager.setPrincipal(currUser.getName());
			return user;
		} else
		{
			return null;
		}
	}
	

	/***
	 * 根据用户名称获取user
	 * 
	 * @param name
	 * @return
	 */
	private static WTUser getUserByName(String name) {
		WTUser user = null;
		try {
			String[] defaultService = OrganizationServicesHelper.manager.getDirectoryServiceNames();
			DirectoryContextProvider dcp = OrganizationServicesHelper.manager
					.newDirectoryContextProvider(defaultService, new String[] { "subtree" });
			Enumeration eee = OrganizationServicesHelper.manager.findLikeUsers("name", name,
					new GenericDirectoryContextProvider(defaultService));
			if (eee.hasMoreElements())
				user = (WTUser) eee.nextElement();
		} catch (WTException wte) {
			wte.printStackTrace();
		}
		return user;
	}


	public static WTOrganization findWTOrganization(String org_name) throws WTException {
		if (org_name != null && !"".equals(org_name)) {
			if (org_name.indexOf("''") > 0) {
				org_name = org_name.replace("''", "''''");
			}
			if (org_name.indexOf("'") > 0) {
				org_name = org_name.replace("'", "''");
			}
		}
		WTOrganization wtOrganization = null;
		String sql = "select t.ida2a2 from wtorganization t where upper(t.name)='" + org_name.toUpperCase() + "'";
		WTConnection wtconnection = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			wtconnection = getWTConnection();
			try {
				pstmt = wtconnection.prepareStatement(sql);
				rs = pstmt.executeQuery();
				while (rs.next()) {
					String ida2a2 = rs.getLong(1) + "";
					wtOrganization = getWTOrganizationByoid(ida2a2);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

		} catch (WTException e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstmt != null) {
					pstmt.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return wtOrganization;
	}

	public static WTConnection getWTConnection() throws WTException {

		WTConnection wtConn = null;

		try {
			MethodContext methodcontext = getMethodContext();
			wtConn = (WTConnection) methodcontext.getConnection();
		} catch (Exception e) {
			throw new WTException(e);
		}

		return wtConn;
	}

	public static WTOrganization getWTOrganizationByoid(String ida2a2) {
		// TODO Auto-generated method stub
		WTOrganization wtOrganization = null;
		boolean accessControlled = false;
		if ("".equals(ida2a2) || ida2a2 == null || "null".equals(ida2a2)) {
			return null;
		}
		long l = Long.parseLong(ida2a2);
		boolean enforce = wt.session.SessionServerHelper.manager.setAccessEnforced(accessControlled);
		try {
			QuerySpec spec = new QuerySpec(WTOrganization.class);
			spec.appendWhere(new SearchCondition(WTOrganization.class, "thePersistInfo.theObjectIdentifier.id",
					SearchCondition.EQUAL, l), new int[] { 0 });

			QueryResult queryResult = PersistenceHelper.manager.find((StatementSpec) spec);
			if (queryResult.hasMoreElements()) {
				wtOrganization = (WTOrganization) queryResult.nextElement();
			}
		} catch (Exception e) {
			// logger.logErrorMsg(e.getMessage(), e);
			System.out.println(e);
		} finally {
			SessionServerHelper.manager.setAccessEnforced(enforce);
		}
		return wtOrganization;

	}

	private static MethodContext getMethodContext() throws WTException {

		MethodContext methodcontext = null;
		methodcontext = MethodContext.getContext();

		return methodcontext;
	}

}
